package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.Page;
import com.yh.correct.model.Register;
import com.yh.correct.model.Report;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IJudicialDeptmentService;
import com.yh.correct.service.IReportService;

/**
 * @author Administrator
 * @注释 : 服刑人员思想汇报控制层
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    private static Logger logger = LogManager.getLogger(ReportController.class);

    @Autowired
    private IReportService reportService;
    /**
     * 注入司法所服务层接口
     */
    @Autowired
    private IJudicialDeptmentService jud;
    /**
     * 注入矫正人员服务层接口
     */
    @Autowired
    private ICorrectedPersonService cor;

    /**
     * 首页跳转
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/skip2")
    public ModelAndView skip() {
        return new ModelAndView("supervision/report");
    }

    /**
     * 增加窗口跳转
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/addSkip")
    public ModelAndView addSkip() {
        return new ModelAndView("supervision/report_add");
    }

    /**
     * 矫正所下拉框显示
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/jselect")
    public List<Object> jShowSelect() {
        List<Object> list = jud.listJudicialDeptments();
        return list;
    }

    /**
     * 矫正人员下拉框显示
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/pselect")
    public List<CorrectedPerson> pShowSelect() {
        List<CorrectedPerson> list = null;
        try {
            list = cor.findCorrectedPerson();
        } catch (Exception e) {

            e.printStackTrace();
        }
        return list;
    }

    /**
     * @author Administrator
     * @注释 : 增加服刑人员思想汇报
     */
    @RequestMapping(value = "/add")
    public ResultData addReport(Report report, String bdate, String scores, String scoreValue) {
        int i = 0;
        Double score = Double.valueOf(scores);
        Double scoreValues = Double.valueOf(scoreValue);
        Date reportDate = null;

        try {
            reportDate = new SimpleDateFormat("yyyy-MM-dd").parse(bdate);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        report.setDate(reportDate);
        report.setScore(score);
        report.setScore_value(scoreValues);
        try {
            i = reportService.addReport(report);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ResultData rd = new ResultData();
        if (i > 0) {
            rd.setCode(0);
            rd.setMessage("增加成功！");
        } else {
            rd.setCode(-1);
            rd.setMessage("增加失败！");
        }
        logger.debug("增加思想汇报! + ReportController");
        return rd;
    }

    /**
     * @author Administrator
     * @注释 : 删除服刑人员思想汇报
     */
    @RequestMapping(value = "/del")
    public ResultData delReport(int id) {
        int i = 0;
        try {
            i = reportService.delReport(id);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ResultData rd = new ResultData();
        if (i > 0) {
            rd.setCode(0);
            rd.setMessage("删除成功");
        } else {
            rd.setCode(-1);
            rd.setMessage("删除失败！");
        }
        logger.debug("删除思想汇报! + ReportController");
        return rd;
    }

    /**
     * 批量删除思想汇报信息
     * @param list
     * @return
     */
    @RequestMapping("/deleteBatch")
    public ResultData deleteBatch(@RequestParam("ids[]") List<Integer> list) {
        ResultData rd = new ResultData();
        int i = 0;
        try {
            i = reportService.deleteBatch(list);
            if (i > 0) {
                rd.setCode(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rd;
    }
    /**
     * 修改前查询单条详细期满登记
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail")
    public ModelAndView getaReport(int id) {
        logger.debug(id);
        Report rg = new Report();
        rg.setId(id);
        Map<String, Object> map = null;
        try {
            map = reportService.getIdReport(id);
            logger.debug(map);
        } catch (Exception e) {

            e.printStackTrace();
        }
        logger.debug("报到登记! + report");
        return new ModelAndView("supervision/report_edit", map);
    }

    /**
     * @author Administrator
     * @注释 : 修改服刑人员思想汇报
     */
    @RequestMapping(value = "/edit")
    public ResultData editReport(Report report, String bdate, String scores, String scoreValue) {
        int i = 0;
        Double score = Double.valueOf(scores);
        Double scoreValues = Double.valueOf(scoreValue);
        Date reportDate = null;

        try {
            reportDate = new SimpleDateFormat("yyyy-MM-dd").parse(bdate);
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        report.setDate(reportDate);
        report.setScore(score);
        report.setScore_value(scoreValues);
        try {
            i = reportService.editReport(report);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ResultData rd = new ResultData();
        if (i > 0) {
            rd.setCode(0);
            rd.setMessage("修改成功");
        } else {
            rd.setCode(-1);
            rd.setMessage("修改失败！");
        }
        logger.debug("修改思想汇报! + ReportController");
        return rd;
    }

    @RequestMapping(value = "/look")
    public ModelAndView getIdReport(Integer id) {

        Map<String, Object> map = new HashMap<String, Object>();

        try {
            map = reportService.getIdReport(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView("supervision/report_look", map);
    }

    /**
     * @author Administrator
     * @注释 : 模糊查询服刑人员思想汇报
     */
    @RequestMapping(value = "/get")
    public ResultData getLikeRegister(String id, String jid, int pageSize, int pageNum) {
        //当id、jid为空时要将其转换为0
        Integer id1 = 0;
        if (!"".equals(id) && null != id) {
            id1 = Integer.parseInt(String.valueOf(id));
        }
        Integer jid1 = 0;
        if (!"".equals(jid) && null != jid) {
            jid1 = Integer.parseInt(String.valueOf(jid));
        }
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("pageSize", pageSize);
        condition.put("pageNum", pageNum);
        condition.put("id", id1);
        condition.put("jid", jid1);
        Page page = null;
        try {
            page = reportService.getListReport(condition);
        } catch (Exception e) {

            e.printStackTrace();
        }
        ResultData rd = new ResultData();
        if (page != null) {
            List<Object> report = new ArrayList();
            report.add(page);
            rd.setCode(0);
            rd.setMessage("查询成功！");
            rd.setData(report);
        } else {
            rd.setCode(-1);
            rd.setMessage("查询失败！");
        }
        logger.debug("查询思想汇报! + ReportController");
        return rd;
    }

    /**
     * 导出Excle
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/excel")
    public String outExcle(HttpServletRequest request, HttpServletResponse response,int[] ids) {
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        try {
//				ids非空时批量导出所选项，否则导出所有
            if (ids != null && ids.length>0) {
                for (int id : ids) {
                    Map<String, Object> map = reportService.getIdReport(id);
                    list.add(map);
                }
            } else {
                list = reportService.getAllReport();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> list1 = outExcelRecord(list);
        String fileName = "矫正人员报到";
        String columnNames[] = {"编号", "矫正单位", "姓名", "汇报时间", "汇报方式", "汇报表现", "得分", "分值", "备注"};
        String keys[] = {"id", "jname", "name", "date", "way", "manifestation", "score_value", "score", "remark"};
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list1, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            try {
                throw e;
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }

    /**
     * 记录要导出的所有信息
     * "date", "way","manifestation","score_value","score","remark"
     *
     * @param projects
     * @return
     */
    public List<Map<String, Object>> outExcelRecord(List<Map<String, Object>> projects) {
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        Map<String, Object> object = null;
        for (int i = 0; i < projects.size(); i++) {
            object = projects.get(i);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("id", object.get("id"));
            mapValue.put("jname", object.get("jname"));
            mapValue.put("name", object.get("name"));
            mapValue.put("date", object.get("date"));
            mapValue.put("way", object.get("way"));
            mapValue.put("manifestation", object.get("manifestation"));
            mapValue.put("score_value", object.get("score_value"));
            mapValue.put("score", object.get("score"));
            mapValue.put("remark", object.get("remark"));
            listmap.add(mapValue);
        }
        return listmap;
    }
}

